package com.aphrodite.util;

import java.util.Vector;

public class TaskQueue extends Thread {

	private static TaskQueue instance;
	private static boolean isRunning;

	public static TaskQueue getInstance() {
		if (instance == null) {
			instance = new TaskQueue();
			// instance.start();
		}
		return instance;
	}

	private final Vector tasks;

	private TaskQueue() {
		tasks = new Vector();
	}

	public void addTask(Task task) {
		tasks.addElement(task);
		synchronized (this.tasks) {
			this.tasks.notify();
		}
	}

	public void run() {
		while (isRunning) {
			while (!tasks.isEmpty()) {
				Task task = (Task) tasks.elementAt(0);
				tasks.removeElementAt(0);
				try {
					task.start();
				} catch (Exception e) {
					System.out.println("Could not run task " + e.toString());
				}
			}
			synchronized (this.tasks) {
				try {
					this.tasks.wait();
				} catch (InterruptedException e) {
					// ignore
				}
			}
		}
	}

	public void start() {
		startServicing();
	}

	public void startServicing() {
		if (!isRunning) {
			instance.start();
		}
	}

	public void stopServicing() {
		isRunning = false;
	}

}
